import numpy as np
from sklearn.metrics import confusion_matrix
from scipy.optimize import linear_sum_assignment

def cluster_accuracy(y_true, y_pred):
    # Step 1: 计算混淆矩阵
    cm = confusion_matrix(y_true, y_pred)
    
    # Step 2: 使用匈牙利算法找到最佳匹配
    row_ind, col_ind = linear_sum_assignment(-cm)  # 最大化匹配
    
    # Step 3: 计算准确率
    matched_count = cm[row_ind, col_ind].sum()
    accuracy = matched_count / len(y_true)
    return accuracy, dict(zip(col_ind, row_ind))

# 示例
y_true = np.array([0, 1, 1, 0, 2, 2, 1])  # 真实标签
y_pred = np.array([1, 0, 0, 1, 2, 2, 0])  # 伪标签

accuracy, mapping = cluster_accuracy(y_true, y_pred)
print(f"Accuracy: {accuracy}")
print(f"Mapping: {mapping}")

